<?php

class G4T_Controller extends Zend_Controller_Action
{
    /**
     * @var Lib_Flash
     */
    protected $_flashMessenger;

    /**
     * @var \Zend_Log
     */
    protected $_logger;

    public function init()
    {
        $this->_validateConnectionType();
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
            $response = $this->getResponse();
            $response->setHeader('Content-Type', 'text/x-json');
        } else {
            $this->_helper->layout()->setLayout('index-layout');
        }
        $this->_flashMessenger = new Lib_Flash();
        $this->_logger = \Zend_Registry::get('g4t.log');
    }

    protected function _validateConnectionType()
    {
        if ($this->_request->isSecure()) {
            $this->_freeSSL();
        }
    }

    protected function displayPaginantor($total, $page, $itemsPerPage)
    {
        $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_Null($total));
        $paginator->setItemCountPerPage($itemsPerPage);
        $paginator->setCurrentPageNumber($page);

        $this->view->paginator = $paginator;
    }

    protected function handleException(Exception $e)
    {
        $this->_logger->log($e->getMessage() . PHP_EOL . $e->getTraceAsString(), \Zend_Log::ERR);
        $this->_flashMessenger->addMessage("Something went wrong!", Lib_Flash::ERROR, Lib_Flash::POST);
    }

    protected function saveCurrentUrl()
    {
        $session = new Zend_Session_Namespace('redirect');
        $session->url = $this->_request->getRequestUri();
    }

    protected function getSavedUrl()
    {
        $session = new Zend_Session_Namespace('redirect');
        $url = $session->url;
        $session->url = false;
        return $url;
    }

    protected function _forceSSL()
    {
        $this->_redirect('https://' . $this->getRequest()->getHttpHost() . $this->getRequest()->getRequestUri());
    }

    protected function _freeSSL()
    {
        $this->_redirect('http://' . $this->getRequest()->getHttpHost() . $this->getRequest()->getRequestUri());
    }

    protected function _getOffset($page, $itemsPerPage)
    {
        return $page > 0 ? ($page - 1) * $itemsPerPage : 0;
    }
}
